<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class SystemConfig extends Backend
{
    
    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        // $this->model = new \app\admin\model\Shop;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ( !$params ) {
                $this->error('请填写完资料');
            }
            foreach ($params as $key => $value) {
                db('system_config')->where(['group'=>'system_configuration','name'=>$key])->update(['value'=>$value]);
            }
            $this->success();
        }
        $list = db('system_config')->where(['group'=>'system_configuration'])->select();
        $row = [];
        foreach ($list as $key => $value) {
            $row[$value['name']] = $value['value'];
        }
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /*
    *提交饭堂运营补贴标准
     */
    public function submitSubsidies($value='')
    {
        $params = $this->request->post("row/a");
        if ( !$params ) {
            $this->error('请填写完资料');
        }

        $subsidies_for_canteen_operation_price = $params['subsidies_for_canteen_operation_price'];
        $subsidies_for_canteen_operation_top_price = $params['subsidies_for_canteen_operation_top_price'];

        if ( !$subsidies_for_canteen_operation_price ) {
            $this->error('请填写每人次多少元');
        }
        if ( $subsidies_for_canteen_operation_price <= 0 ) {
            $this->error('每人次不可以小于或等于0元');
        }
        if ( !$subsidies_for_canteen_operation_top_price ) {
            $this->error('请填写每年上限多少元');
        }
        if ( $subsidies_for_canteen_operation_top_price <= 0 ) {
            $this->error('每年上限次不可以小于或等于0元');
        }

        $row = db('cookbook_subsidy_price')->find();

        $status = db('cookbook_subsidy_price')->where(['id'=>$row['id']])->update(['subsidies_for_canteen_operation_price'=>$subsidies_for_canteen_operation_price,'subsidies_for_canteen_operation_top_price'=>$subsidies_for_canteen_operation_top_price]);

        if ( $status === false ) {
            $this->error('修改失败');
        }
        insert_admin_log_user($this->auth->id,'修改饭堂运营补贴标准',1);
        $this->success();

    }

    /*
    *提交饭堂运营补贴标准
     */
    public function submitSubsidiesPrice($value='')
    {
        $params = $this->request->post("row/a");
        if ( !$params ) {
            $this->error('请填写完资料');
        }

        $age_1 = $params['age_1'];
        $age_2 = $params['age_2'];
        $special_elders_subsidy_price = $params['special_elders_subsidy_price'];
        $other_special_elders_subsidy_price = $params['other_special_elders_subsidy_price'];

        if ( !$age_1 ) {
            $this->error('请填写本区60-79周岁补贴');
        }
        if ( $age_1 <= 0 ) {
            $this->error('本区60-79周岁补贴不可以小于或等于0元');
        }
        if ( !$age_2 ) {
            $this->error('请填写本区80周岁及以上补贴');
        }
        if ( $age_2 <= 0 ) {
            $this->error('本区80周岁及以上补贴不可以小于或等于0元');
        }
        if ( !$special_elders_subsidy_price ) {
            $this->error('请填写本区特殊老人补贴');
        }
        if ( $special_elders_subsidy_price <= 0 ) {
            $this->error('本区本区特殊老人补贴不可以小于或等于0元');
        }
        if ( !$other_special_elders_subsidy_price ) {
            $this->error('请填写外市老人及特殊老人补贴');
        }
        if ( $other_special_elders_subsidy_price <= 0 ) {
            $this->error('外市老人及特殊老人补贴不可以小于或等于0元');
        }

        $row = db('cookbook_subsidy_price')->find();

        $result = false;
        Db::startTrans();
        try {
        $result = db('cookbook_subsidy_price')->where(['id'=>$row['id']])->update(['special_elders_subsidy_price'=>$special_elders_subsidy_price,'other_special_elders_subsidy_price'=>$other_special_elders_subsidy_price]);
        $age_1 = db('age')->where(['age_id'=>1])->update(['mechanism_subsidy_price'=>$age_1]);
        $age_2 = db('age')->where(['age_id'=>2])->update(['mechanism_subsidy_price'=>$age_2]);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result !== false && $age_1 !== false && $age_2 !== false) {
            insert_admin_log_user($this->auth->id,'修改饭堂运营补贴标准',1);
            $this->success();
        } else {
            $this->error(__('No rows were inserted'));
        }

        $this->success();

    }
    

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $shop_user = db('shop')->where(['mobile'=>$params['mobile']])->count();
                if ( $shop_user ) {
                    $this->error('登录手机号已经存在');
                }
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['createtime'] = time();
                    $params['admin_id'] = (int)$this->auth->id;

                    $salt = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $salt);
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $administrative_division = db('administrative_division')
            ->where(['is_del'=>0])
            ->select();

        // $shop_status[0] = '筹备中';
        $shop_status[1] = '运营中';
        $shop_status[2] = '停运';

        $this->view->assign("shop_status", $shop_status);
        $this->view->assign("administrative_division", $administrative_division);
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $shop_user = db('shop')->where(['mobile'=>$params['mobile'],'shop_id'=>['neq',$row->shop_id]])->count();
                if ( $shop_user ) {
                    $this->error('登录手机号已经存在');
                }
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = (int)$this->auth->id;
                    if ( $params['password'] ) {
                        $params['password'] = md5(md5($params['password']) . $salt);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $administrative_division = db('administrative_division')
            ->where(['is_del'=>0])
            ->select();
        // $shop_status[0] = '筹备中';
        $shop_status[1] = '运营中';
        $shop_status[2] = '停运';

        $this->view->assign("shop_status", $shop_status);

        $this->view->assign("administrative_division", $administrative_division);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->save(['is_del'=>1]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 停止合作
     */
    public function stopCooperation($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->save(['status'=>2]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $this->error(__('操作失败', 'ids'));
    }

    /**
     * 启用合作
     */
    public function openCooperation($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->save(['status'=>1]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $this->error(__('操作失败', 'ids'));
    }
    
    

}
